const fs = require("fs");
const path = require("path");
const updateFile = (filePath, regx, context) => {
  let data = fs.readFileSync(filePath, "utf-8");
  data = data.replace(regx, (a, b, c) => {
    a = a.replace(b, `${context.name}`);
    return a;
  });
  fs.writeFileSync(filePath, data);
};
const readDir = (destPath, regx, context) => {
  return new Promise((resolve, reject) => {
    const dirFiles = fs.readdirSync(destPath);
    dirFiles.forEach((item) => {
      const newItem = item.replace(regx, (a, b, c) => {
        a = a.replace(b, `${context.name}`);
        return a;
      });
      if (newItem !== item) {
        fs.renameSync(
          path.resolve(destPath, item),
          path.resolve(destPath, newItem)
        );
      }
      if (fs.statSync(path.resolve(destPath, newItem)).isDirectory()) {
        readDir(path.resolve(destPath, newItem), regx, context);
      } else {
        updateFile(path.resolve(destPath, newItem), regx, context);
      }
    });
    resolve();
  });
};

module.exports = (context, ops) => {
  return new Promise((resolve, reject) => {
    const { localScaffoldPath, localTemplatePath, destPath } = ops;
    if (fs.statSync(localScaffoldPath).isDirectory()) {
      const regx = new RegExp(
        context.metadata.projectDevelopLang === "typescript"
          ? "(AwesomeTSProject)|(awesometsproject)"
          : "(AwesomeProject)|(awesomeproject)",
        "gim"
      );
      fs.cp(localScaffoldPath, destPath, { recursive: true }, (err) => {
        if (err) {
          reject(err);
          return;
        }
        if (fs.statSync(localTemplatePath).isDirectory()) {
          fs.cp(localTemplatePath, destPath, { recursive: true }, (err) => {
            if (err) {
              reject(err);
              return;
            }
            readDir(destPath, regx, context)
              .then(() => {
                resolve(context);
              })
              .catch((err) => {
                resolve(context);
              });
          });
        }
      });
    } else {
      resolve(context);
    }
  });
};
